package com.hb.back.controller;


import com.aliyun.tea.TeaException;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.req.UploadVideoRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyun.vod.upload.resp.UploadVideoResponse;
import com.aliyun.vod20170321.models.GetPlayInfoResponseBody;
import com.hb.common.domain.EduVideo;
import com.hb.common.service.EduVideoService;
import com.hb.common.vo.ResultVo;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/video")
public class VideoController {

    @Value("${ali.endpoint}")
    private String endpoint;
    @Value("${ali.bucketName}")
    private String   bucketName;
    @Value("${ali.accessKeyId}")
    private String accessKeyId;
    @Value("${ali.secretAccessKey}")
    private String secretAccessKey;
    @Value("${web.file}")
    private String uploadPath;
    @Autowired
    EduVideoService eduVideoService;
    public  com.aliyun.vod20170321.Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(accessKeyId)
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(secretAccessKey);
        // Endpoint 请参考 https://api.aliyun.com/product/vod
        config.endpoint = "vod.cn-shanghai.aliyuncs.com";
        return new com.aliyun.vod20170321.Client(config);
    }

  @GetMapping("/getPalyUrl/{vid}")
  @Operation(summary = "视频播放地址")
  public ResultVo getPalyUrl(@PathVariable String vid) throws Exception {
      com.aliyun.vod20170321.Client client = this.createClient();
      com.aliyun.vod20170321.models.GetVideoPlayAuthRequest getVideoPlayAuthRequest = new com.aliyun.vod20170321.models.GetVideoPlayAuthRequest()
              .setVideoId(vid);
      com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
      try {
          // 复制代码运行请自行打印 API 的返回值
          com.aliyun.vod20170321.models.GetVideoPlayAuthResponse resp = client.getVideoPlayAuthWithOptions(getVideoPlayAuthRequest, runtime);
          com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(resp));
          return ResultVo.success("视频凭证获取成功!！",resp.getBody().playAuth);

      }catch (Exception error) {
          // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
          // 错误 message
          System.out.println(error.getMessage());
//          // 诊断地址
//          System.out.println(error.getData().get("Recommend"));
//          com.aliyun.teautil.Common.assertAsString(error.message);
          return ResultVo.error("视频凭证获取失败！",error.getMessage());
      }
  }

    @PostMapping("/file")
    @Operation(summary = "上传文件")
    public ResultVo video(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName=UUID.randomUUID().toString()+substring;
        UploadStreamRequest request = new UploadStreamRequest(accessKeyId, secretAccessKey, originalFilename, fileName, file.getInputStream());
        /* 是否使用默认水印(可选)，指定模板组ID时，根据模板组配置确定是否使用默认水印*/
        request.setShowWaterMark(true);
        /* 视频分类ID(可选) */
         request.setCateId(1000590406l);
        /* 封面图片(可选) */
        request.setCoverURL("\thttps://www.jf3q.com/upload_imgs/jf3q/jf_ad_imgs/2021120813221645caf0ba0c7940a7867c8f01b4110b99.jpeg");
        /* 模板组ID(可选) */
        request.setTemplateGroupId("479d04ea3dae87b178cce4d5678d4f7f");
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(request);
        System.out.print("RequestId=" + response.getRequestId() + "\n");  //请求视频点播服务的请求ID
        if (response.isSuccess()) {
            System.out.print("VideoId=" + response.getVideoId() + "\n");
            return ResultVo.success("文件上传成功！",response.getVideoId());
        }else{ //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
            System.out.print("VideoId=" + response.getVideoId() + "\n");
            System.out.print("ErrorCode=" + response.getCode() + "\n");
            System.out.print("ErrorMessage=" + response.getMessage() + "\n");
            return ResultVo.error("文件上传失败！",response.getMessage());
        }
    }

    @PostMapping("/seave")
    public ResultVo seave(@RequestBody EduVideo video){
        boolean save = eduVideoService.save(video);
        if (save){
        return ResultVo.success("添加课时成功!",null);
        }
        return ResultVo.error("添加课时失败!",null);
    }

    @PostMapping("/getUpload")
    public ResultVo getUpload(@RequestBody EduVideo video){
        boolean save = eduVideoService.saveOrUpdate(video);
        if (save){
            return ResultVo.success("修改课时成功!",null);
        }
        return ResultVo.error("修改课时失败!",null);
    }

    @GetMapping("getId/{id}")
    public ResultVo get(@PathVariable String id){
        EduVideo byId = eduVideoService.getById(id);
        if (byId!=null){
            return ResultVo.success("",byId);
        }else{
            return ResultVo.error("",null);
        }
   }

    @GetMapping("del/{id}")
    public ResultVo getdel(@PathVariable String id){
        boolean b = eduVideoService.removeById(id);
        if (b){
            return ResultVo.success("",null);
        }
            return ResultVo.error("",null);
}

    @GetMapping("/huixian/{id}")
    public ResultVo gethuixian(@PathVariable String id){
        EduVideo byId = eduVideoService.getById(id);
        if (byId!=null){
            return ResultVo.success("",byId);
        }
        return ResultVo.error("",null);
     }

}
